//
//  ViewController.m
//  Weather-Test
//
//  Created by My Mac on 2017/4/30.
//  Copyright © 2017年 My Mac. All rights reserved.
//

//宏定义
#define KScreenWidth [UIScreen mainScreen].bounds.size.width

#define KScreenHeight [UIScreen mainScreen].bounds.size.height

#define KScreenBounds [UIScreen mainScreen].bounds
//pix :像素
#define WidthPix KScreenWidth/320
//按Iphone5像素比例分配
#define HeightPix KScreenHeight/568

#import "ViewController.h"
#import "Location.h"
#import "CityTableViewController.h"
#import "AFNetworking.h"
#import "SearchViewController.h"
@interface ViewController ()

//切换城市按钮
@property(nonatomic,strong) UIButton *changeCityBtn;
//背景图片
@property(nonatomic,strong) UIImageView *backGroundImageView;
//创建http
@property(nonatomic,strong) AFHTTPSessionManager *httpManager;
/*
 小鸟
 */
@property(nonatomic,strong) UIImageView *birdImg;

/*
 晴天背景动画
 */
//太阳
@property(nonatomic,strong) UIImageView *sunImg;
//太阳光
@property(nonatomic,strong) UIImageView *sunshineImg;
//晴天云
@property(nonatomic,strong) UIImageView *sunCloudImg;

/*
 多云 云朵位移动画
 */
//云朵 1
@property(nonatomic,strong) UIImageView *cloudOneImg;
//云朵 2
@property(nonatomic,strong) UIImageView *cloudTwoImg;

/*
 雨天背景动画
 */
//乌云
@property(nonatomic,strong) UIImageView *rainCloudImg;
//雨滴
@property(nonatomic,strong) UIImageView *rainDropImg;
//雨滴数组
@property(nonatomic,strong) NSArray *rainDropsArr;

/*
 下雪天
 */
//雪花
@property(nonatomic,strong) UIImageView *snowImg;
//下雪的云
@property(nonatomic,strong) UIImageView *snowColudImg;
//雪花数组
@property(nonatomic,strong) NSArray *snowsArr;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化控件
    [self initViews];
    
    //获取用户当前位置
    [self getUserLocation];
    NSLog(@"%@",_cityName);
    [self SenderRequest:_cityName];
}

-(void)initViews
{
    _backGroundImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg_normal"]];
    _backGroundImageView.frame = self.view.bounds;
    [self.view addSubview:_backGroundImageView];
    
    
    _changeCityBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //设置button的frame
    _changeCityBtn.frame = CGRectMake(KScreenWidth-54, 20, 44, 44);
    //设置button的间距
    [_changeCityBtn setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    //设置按钮的图片
    [_changeCityBtn setImage:[UIImage imageNamed:@"location_hardware"] forState:UIControlStateNormal];
    //设置响应事件
    [_changeCityBtn addTarget:self action:@selector(changeCity) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_changeCityBtn];
}

-(void)changeCity
{
    CityTableViewController *cityTableView = [[CityTableViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:cityTableView];
    //设置导航栏背景
    [nav.navigationBar setBackgroundImage:[UIImage imageNamed:@"navBg3"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    //设置导航栏字体颜色
    [nav.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    //设置导航栏上的按钮颜色为白色
    nav.navigationBar.tintColor = [UIColor whiteColor];
    
    [self presentViewController:nav animated:YES completion:nil];
    [cityTableView setGetCityName:^void(NSString *cityName){
        NSLog(@"%@",cityName);
        [self SenderRequest:cityName];
    }];
}

//天气请求方法
-(void)SenderRequest:(NSString *)cityName
{
    _httpManager = [AFHTTPSessionManager manager];
    NSString *urlString = [NSString stringWithFormat:@"https://api.thinkpage.cn/v3/weather/daily.json?key=yvmfe43vktyumwk5&location=%@&language=zh-Hans&start=0&days=3",cityName];
    //字符转译
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [_httpManager GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功
        NSArray *resultArr = responseObject[@"results"];
        for (NSDictionary *dict in resultArr) {
            //调用移除动画方法
            [self removeAnimationFromView];
            NSInteger type = [dict[@"daily"][0][@"code_day"] integerValue];
            NSLog(@"code_day:%ld",[dict[@"daily"][0][@"code_day"] integerValue]);
            
            if (type>=0 && type<4) {
                //晴天
                [self sunshineAnimation];
            }else if (type>= 4 && type<10){
                //多云
                [self windAnimation];
            }else if (type >=10 && type <20){
                //下雨
                [self rainAnimation];
            }else if (type >=20 && type <26){
                //下雪
                [self snowAnimation];
            }
        }
        
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        NSLog(@"请求失败");
    }];
}

#pragma mark - 下雪动画效果
-(void)snowAnimation
{
    [self changeBackGroundImg:[UIImage imageNamed:@"bg_snow_night"]];
    /**
     * 下雪的云
     */
    _snowColudImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"4"]];
    [self setImageView:_snowColudImg size:CGSizeMake(KScreenHeight*0.3, KScreenWidth*0.5) center:CGPointMake(KScreenWidth*0.5, KScreenHeight*0.3) animation:nil];
    
    /**
     * 雪花
     */
    _snowsArr = [self getJsonArrData];
    for(int i=0; i<_snowsArr.count; i++){
        NSDictionary *dictJson = _snowsArr[i];
        //获取图片名
        _snowImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"snow"]];
        //设置tag，区分rainDropImg
        _snowImg.tag = 200 + i;
        //获取size，并分割为数组
        NSArray *rainDropSize = [dictJson[@"-size"] componentsSeparatedByString:@","];
        //获取origin 起源坐标，并分割为数组
        NSArray *rainDropOrigin = [dictJson[@"-origin"] componentsSeparatedByString:@","];
        //取出数组相应坐标值/大小值,并赋值给rainDropImg的frame
        _snowImg.frame = CGRectMake([rainDropOrigin[0] integerValue]*WidthPix, [rainDropOrigin[1] integerValue], [rainDropSize[0] integerValue], [rainDropSize[1] integerValue]-60);
        [self.view addSubview:_snowImg];
        //根据i值设置动画速度(时间)
        [_snowImg.layer addAnimation:[self setRainDropsAnimationWithDuration:2 + i%5] forKey:nil];
        //根据i值设置动画透明度
        [_snowImg.layer addAnimation:[self setAlphaAnimationWithDuration:2 + i%5] forKey:nil];
        [_snowImg.layer addAnimation:[self setRotateAnimationWithDuration:350.0f] forKey:nil];
    }
}

#pragma mark - 雨天动画效果
-(void)rainAnimation
{
    [self changeBackGroundImg:[UIImage imageNamed:@"bg_rain_day"]];
    /**
     * 乌云
     */
    _rainCloudImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"night_rain_cloud"]];
    [self setImageView:_rainCloudImg size:CGSizeMake(768/371.0 *KScreenWidth*0.5, KScreenWidth*0.5) center:CGPointMake(KScreenWidth*0.25, KScreenHeight*0.1) animation:[self setTranslationAnimationWithValue:[NSNumber numberWithFloat:350.0f] duration:50]];
    
    /**
     * 雨滴
     */
    _rainDropsArr = [self getJsonArrData];
    for(int i=0; i<_rainDropsArr.count; i++){
        NSDictionary *dictJson = _rainDropsArr[i];
        //获取图片名
        _rainDropImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:dictJson[@"-imageName"]]];
        //设置tag，区分rainDropImg
        _rainDropImg.tag = 100 + i;
        //获取size，并分割为数组
        NSArray *rainDropSize = [dictJson[@"-size"] componentsSeparatedByString:@","];
        //获取origin 起源坐标，并分割为数组
        NSArray *rainDropOrigin = [dictJson[@"-origin"] componentsSeparatedByString:@","];
        //取出数组相应坐标值/大小值,并赋值给rainDropImg的frame
        _rainDropImg.frame = CGRectMake([rainDropOrigin[0] integerValue]*WidthPix, [rainDropOrigin[1] integerValue], [rainDropSize[0] integerValue], [rainDropSize[1] integerValue]);
        [self.view addSubview:_rainDropImg];
        //根据i值设置动画速度(时间)
        [_rainDropImg.layer addAnimation:[self setRainDropsAnimationWithDuration:2 + i%5] forKey:nil];
        //根据i值设置动画透明度
        [_rainDropImg.layer addAnimation:[self setAlphaAnimationWithDuration:2 + i%5] forKey:nil];
    }
}


#pragma mark - 获取json数据
-(NSArray *)getJsonArrData
{
    NSString *rainPath = [[NSBundle mainBundle] pathForResource:@"rainData.json" ofType:nil];
    //把json文件转成data格式
    NSData *dataJson = [NSData dataWithContentsOfFile:rainPath];
    //将dataJson数组转为字典
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:dataJson options:NSJSONReadingMutableContainers error:nil];
    //取值
    return dict[@"weather"][@"image"];
}

#pragma mark - 多云动画效果
- (void)windAnimation
{
    //多云背景
    [self changeBackGroundImg:[UIImage imageNamed:@"bg_normal"]];
    //云朵 1
    _cloudOneImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ele_sunnyCloud1"]];
    [self setImageView:_cloudOneImg size:CGSizeMake(KScreenHeight*0.1, KScreenWidth*0.5) center:CGPointMake(0, KScreenHeight *0.7) animation:[self setTranslationAnimationWithValue:[NSNumber numberWithFloat:KScreenWidth] duration:5.0f]];
    
    //云朵 2
    _cloudTwoImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ele_sunnyCloud2"]];
    [self setImageView:_cloudOneImg size:CGSizeMake(KScreenHeight*0.1, KScreenWidth*0.25) center:CGPointMake(0, KScreenHeight *0.5) animation:[self setTranslationAnimationWithValue:[NSNumber numberWithFloat:350.0f] duration:30.0]];
    
    
}

#pragma mark - 晴天动画效果
- (void)sunshineAnimation
{
    //晴天背景
    [self changeBackGroundImg:[UIImage imageNamed:@"bg_sunny_day"]];
    /**
     * 太阳
     */
    _sunImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ele_sunnySun"]];
    [self setImageView:_sunImg size:CGSizeMake(200, 200*579/612.0) center:CGPointMake(KScreenWidth*0.2, KScreenHeight*0.1) animation:[self setRotateAnimationWithDuration:5.0f]];
    
    /**
     * 太阳光
     */
    _sunshineImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ele_sunnySunshine"]];
    [self setImageView:_sunshineImg size:CGSizeMake(200, 200*579/612.0) center:CGPointMake(KScreenWidth*0.2, KScreenHeight*0.1) animation:[self setRotateAnimationWithDuration:5.0f]];
    
    /**
     * 晴天云
     */
    _sunCloudImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ele_sunnyCloud2"]];
    [self setImageView:_sunCloudImg size:CGSizeMake(KScreenWidth*0.2, KScreenHeight*0.4) center:CGPointMake(0, KScreenHeight*0.4) animation:[self setTranslationAnimationWithValue:[NSNumber numberWithFloat:KScreenWidth] duration:5.0f]];
}

#pragma mark - 动画细节封装
-(void)setImageView:(UIImageView *)imageView size:(CGSize)size center:(CGPoint)center animation:(CAAnimation *)animation
{
    //把太阳的大小赋给frameSun
    CGRect frame = imageView.frame;
    //给frameSun按比例缩小
    frame.size = size;
    //imageView.frame = frame;
    //设置中心坐标点
    imageView.center = center;
    [self.view addSubview:imageView];
    //添加动画
    [imageView.layer addAnimation:animation forKey:nil];
}

#pragma mark - 雨滴透明度动画
-(CABasicAnimation *)setAlphaAnimationWithDuration:(NSInteger)duration
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    //透明度 1:不透明,0:全透明
    [animation setFromValue:[NSNumber numberWithFloat:1.0]];
    [animation setFromValue:[NSNumber numberWithFloat:0.1]];
    [animation setDuration:duration];
    [animation setRepeatCount:MAXFLOAT];
    [animation setFillMode:kCAFillModeForwards];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
    [animation setRemovedOnCompletion:NO];
    return animation;
}

#pragma mark - 雨滴落下动画
-(CABasicAnimation *)setRainDropsAnimationWithDuration:(NSInteger)duration
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    [animation setDuration:duration];
    [animation setRepeatCount:MAXFLOAT];
    //动画完成后不移除,并保留执行后的状态
    [animation setRemovedOnCompletion:NO];
    [animation setFillMode:kCAFillModeForwards];
    //设置X,Y,Z 开始坐标
    [animation setFromValue:[NSValue valueWithCATransform3D:CATransform3DMakeTranslation(-170, -620, 0)]];
    [animation setToValue:[NSValue valueWithCATransform3D:CATransform3DMakeTranslation(KScreenHeight/2.0*34/124.0, KScreenHeight/2, 0)]];
    return animation;
}

#pragma mark - 水平方向移动动画
-(CABasicAnimation *)setTranslationAnimationWithValue:(NSNumber *)value duration:(NSInteger)duration
{
    //设置水平移动动画 沿着x轴移动
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
    //到某个值
    [animation setToValue:value];
    //动画时间
    [animation setDuration:duration];
    //动画重复次数
    [animation setRepeatCount:MAXFLOAT];
    return animation;
}

#pragma mark - 旋转动画方法
-(CABasicAnimation *)setRotateAnimationWithDuration:(NSInteger)duration
{
    //创建单一动画类CABasicAnmation 沿着z轴旋转
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //基本动画设置
    //旋转角度: 360°
    [animation setToValue:[NSNumber numberWithFloat:2 * M_PI]];
    //旋转次数
    [animation setRepeatCount:HUGE_VALF];
    //动画持续时间
    [animation setDuration:duration];
    //动画完成不移除
    [animation setRemovedOnCompletion:NO];
    [animation setFillMode:kCAFillModeForwards];
    return animation;
}

#pragma mark - 封装背景图片渐变动画
-(void)changeBackGroundImg:(UIImage *)image
{
    //创建动画
    CATransition *transition = [CATransition animation];
    //动画时间
    [transition setDuration:1];
    //设置动画效果，先慢后快
    [transition setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
    //动画类型为过滤效果
    [transition setType:kCATransitionFade];
    //背景图片绑定动画
    [_backGroundImageView.layer addAnimation:transition forKey:@"a"];
    //设置接收到的图片
    [_backGroundImageView setImage:image];
}

-(void)removeAnimationFromView
{
    [_sunImg removeFromSuperview];
    [_sunCloudImg removeFromSuperview];
    [_sunshineImg removeFromSuperview];
    [_rainCloudImg removeFromSuperview];
    [_cloudOneImg removeFromSuperview];
    [_cloudTwoImg removeFromSuperview];
    [_cloudTwoImg removeFromSuperview];
    [_snowColudImg removeFromSuperview];
    for (NSInteger i = 0; i< _rainDropsArr.count; i++) {
        _rainDropImg = [self.view viewWithTag:100+i];
        [_rainDropImg removeFromSuperview];
        _snowImg = [self.view viewWithTag:200+i];
        [_snowImg removeFromSuperview];
    }
}

#pragma mark - 获取定位
-(void)getUserLocation
{
    [Location getUserLocation:^(double lat, double lon, NSString *cityName) {
        NSLog(@"lat: %lf,lon:%lf,cityName:%@",lat,lon,cityName);
    }];
}
@end
